import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import { fetchValidation } from '@/utils';
import {
  queryCampusDepartment,
  querySaveDepartmentList,
  performSaveDepartment,
  performDeleteDepartment,
} from './service';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    deleteDepartment: Effect;
    saveDepartmentList: Effect;
    saveDepartment: Effect;
  };
  reducers: {
    save: Reducer;
    lookup: Reducer;
    clear:Reducer;
  };
}

const Model: ModelType = {
  namespace: 'campusCommunityDepartment',

  state: {
    departmentInfo: {
      list: [],
      count: 0,
    },
    lookupList: {
      count: 0,
      list: [],
    },
  },

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryCampusDepartment, payload);
      const data = fetchValidation(response);

      if (data) {
        yield put({
          type: 'save',
          payload: response.body,
        });
      }
    },

    * deleteDepartment({ payload: { fetchValues, deleteValues } }, { call, put }) {
      const response = yield call(performDeleteDepartment, { ...deleteValues });
      const data = fetchValidation(response);

      if (data) {
        message.success('删除成功');
        yield put({
          type: 'fetch',
          payload: fetchValues,
        });
      }
    },

    * saveDepartmentList({ payload }, { call, put }) {
      const response = yield call(querySaveDepartmentList, payload);
      const data = fetchValidation(response);

      if (data) {
        yield put({
          type: 'lookup',
          payload: response.body,
        });
      }
    },

    * saveDepartment({ payload: { fetchValues, saveValues } }, { call, put }) {
      const response = yield call(performSaveDepartment, { ...saveValues });
      const data = fetchValidation(response);

      if (data) {
        message.success('添加成功');
        yield put({
          type: 'fetch',
          payload: fetchValues,
        });
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        departmentInfo: action.payload,
      };
    },
    lookup(state, action) {
      return {
        ...state,
        lookupList: action.payload,
      };
    },
    clear(){
      return {
        departmentInfo: {
          list: [],
          count: 0,
        },
        lookupList: {
          count: 0,
          list: [],
        },
      }
    }
  },
};

export default Model;
